package cn.gogpay.dcb.api.web;

import cn.gogpay.dcb.api.dto.qrcode.QueryConsumeRecordDTO;
import cn.gogpay.dcb.api.entity.GoodsItem;
import cn.gogpay.dcb.api.entity.OrderRecord;
import cn.gogpay.dcb.api.entity.UserBusCard;
import cn.gogpay.dcb.api.feign.ApiPlatformClient;
import cn.gogpay.dcb.api.service.*;
import cn.gogpay.dcb.api.web.base.BaseController;
import cn.gogpay.dcb.api.web.form.CreateOrderForm;
import cn.gogpay.dcb.api.web.form.StationInfoForm;
import cn.gogpay.dcb.common.dto.ResultCode;
import cn.gogpay.dcb.common.dto.ResultDTO;
import cn.gogpay.dcb.common.util.lang.StringUtils;
import cn.gogpay.dcb.h5base.dto.UserDTO;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 说明
 *
 * @author jiaoming@gogpay.cn
 * @date 2019/11/22 18:45
 */
@RequestMapping("/api/qrCode/")
@Controller
public class ApiController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

    @Value("${spring.profiles.active}")
    private String profiles;

    @Autowired
    private ApiPlatformClient apiPlatformClient;

    @Autowired
    private UserBusCardService userBusCardService;

    @Autowired
    private GoodsItemService goodsItemService;

    @Autowired
    private RechargeRecordService rechargeRecordService;

    @Autowired
    private OutService outService;

    @Autowired
    private PublicTrafficService publicTrafficService;

    /**
     * 判断用户是否实名认证
     *
     * @param request
     * @return
     */

    private boolean hasAuth(HttpServletRequest request) {
        String authCardNo = this.getUserInfo(request).getAuthCardNo();

        /**
         * 身份证号号码为空，说明没有进行实名认证
         */
        if (StringUtils.isNotEmpty(authCardNo)) {
            return true;
        }
        return false;
    }

    /**
     * 开卡
     *
     * @return
     */
    @PostMapping("/activateCard")
    @ResponseBody
    public ResultDTO activateCard(HttpServletRequest request) {
        UserDTO userInfo = this.getUserInfo(request);
        return this.userBusCardService.activeCard(userInfo.getUserId(), userInfo.getPhoneNo());
    }


    /**
     * 拉取二维码
     *
     * @return
     */
    @PostMapping("/pullQrCode")
    @ResponseBody
    public ResultDTO pullQrCode(HttpServletRequest request) {
        UserDTO userInfo = this.getUserInfo(request);
        /**
         * 1、检查是否实名认证
         */
        /*if (!this.hasAuth(request)) {
            ResultDTO resultDTO = new ResultDTO(1006, "请实名", new Object());
            return resultDTO;
        }*/
        /**
         * 2、检查是否已经开卡
         */
        if (!this.userBusCardService.hasOpenBusCard(userInfo.getUserId())) {
            ResultDTO resultDTO = this.userBusCardService.activeCard(userInfo.getUserId(), userInfo.getPhoneNo());
            if (resultDTO.getStatus() != ResultCode.SUCCESS_CODE) {
                return new ResultDTO(1007, "请开卡", new Object());
            }
        }
        UserBusCard cardInfo = userBusCardService.findByUserId(userInfo.getUserId());
        ResultDTO resultDTO = this.userBusCardService.pullQrCode(userInfo.getUserId(), userInfo.getPhoneNo());

        JSONObject data = (JSONObject) resultDTO.getData();
        if (null == data) {
            data = new JSONObject();
        }
        data.put("cardInfo", cardInfo);
        resultDTO.setData(data);

        int code = resultDTO.getStatus();
        String msg = resultDTO.getMsg();
        if (-1 == code) {
            if (!StringUtils.isEmpty(msg) && msg.contains("不存在")) {
                return new ResultDTO(1007, "请开卡", new Object());
            }
            if (!StringUtils.isEmpty(msg) && msg.contains("余额")) {
                return new ResultDTO(10005, "余额不足", new Object());
            }
        }
        return resultDTO;
    }


    /**
     * 余额查询
     *
     * @return
     */
    @PostMapping("/getBalance")
    @ResponseBody
    public ResultDTO getBalance(HttpServletRequest request) {
        UserDTO userInfo = this.getUserInfo(request);
        return this.userBusCardService.getBalance(userInfo.getPhoneNo());
    }

    /**
     * 余额查询
     *
     * @return
     */
    @RequestMapping("/getPriceList")
    @ResponseBody
    public ResultDTO getPriceList(HttpServletRequest request) {
        UserDTO userInfo = this.getUserInfo(request);
        List<GoodsItem> list = this.goodsItemService.getAll();

        return new ResultDTO(200, "success", list);
    }

    /**
     * 查询乘车明细
     *
     * @return
     */
    @GetMapping("/consumeRecord")
    @ResponseBody
    public ResultDTO consumeRecord(HttpServletRequest request) {

        UserDTO userInfo = this.getUserInfo(request);

        QueryConsumeRecordDTO queryConsumeRecordDTO = new QueryConsumeRecordDTO();
        queryConsumeRecordDTO.setUserPhone(userInfo.getPhoneNo());

        ResultDTO resultDTO = this.apiPlatformClient.consumeRecord(queryConsumeRecordDTO);
        logger.info("[查询乘车明细api-platform请求返回结果][{}]", resultDTO);
        if (!resultDTO.isSuccess()) {
            return resultDTO;
        }
        JSONObject data = (JSONObject) resultDTO.getData();
        if ("200".equals(data.getString("code"))) {
            /**
             dealNo  明细编号
             dealMoney 乘车交易金额
             dealType 交易类型
             dealStatus  交易状态
             dealTime  交易时间，格式：yyyy-MM-dd HH:mm:ss
             accountNo 订单编号
             busLine  公交线路
             logicalcardNo  卡号
             debitTime   扣款时间，格式：yyyy-MM-dd HH:mm:ss
             beforeAccoun 交易前金额
             afterAccount 交易后金额
             userPhone 用户手机号
             */
            JSONArray result = data.getJSONArray("result");
            logger.info("[查询乘车明细], result={}", result);
            return new ResultDTO(200, "success", result);
        }
        return new ResultDTO(500, data.getString("msg"));
    }


    /**
     * 失物招领
     *
     * @return
     */
    @PostMapping("/getLoseList")
    @ResponseBody
    public ResultDTO getLoseList() {
        ResultDTO resultDTO = this.apiPlatformClient.getLostList();
        return resultDTO;
    }

    /**
     * 新闻资讯
     *
     * @return
     */
    @PostMapping("/getNewsList")
    @ResponseBody
    public ResultDTO getNewsList() {
        ResultDTO resultDTO = this.apiPlatformClient.getNewsList();
        return resultDTO;
    }

    /**
     * 网点分布
     *
     * @return
     */
    @PostMapping("/getBankShowNodeList")
    @ResponseBody
    public ResultDTO getBankShowNodeList() {
        List<GoodsItem> list = goodsItemService.getAll();
        ResultDTO resultDTO = new ResultDTO(200, "", list);
        return resultDTO;
    }

    /**
     * 创建订单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/createOrder")
    ResultDTO createOrder(@RequestBody CreateOrderForm form, HttpServletRequest request) {
        logger.info("创建订单入参---------------->" + JSONObject.toJSONString(form));
        this.beanValidator(form);
        String priceId = form.getPriceId();
        String price = form.getPrice();
        GoodsItem goodsItem = new GoodsItem();
        if (!StringUtils.isEmpty(priceId)) {
            goodsItem = goodsItemService.findOne(priceId);
        } else {
            goodsItem.setId("0");
            goodsItem.setPrice(new BigDecimal(price));
        }
        if (StringUtils.isEmpty(goodsItem.getPrice())) {
            return new ResultDTO(500, "充值金额合法");
        }
        UserDTO userDTO = getUserInfo(request);

        OrderRecord record = rechargeRecordService.createThirdOrder(userDTO, goodsItem);
        return rechargeRecordService.getOrderParams(record);
    }

    /**
     * 余额查询
     *
     * @return
     */
    @GetMapping("getOrderRecord")
    @ResponseBody
    public ResultDTO getOrderRecord(HttpServletRequest request, @Param("orderNo") String orderNo) {
        OrderRecord record = rechargeRecordService.findByOrderNo(orderNo);
        return new ResultDTO(200, "success", record);
    }

    /**
     * 订单井记录
     *
     * @return
     */
    @GetMapping("getOrderRecordList")
    @ResponseBody
    public ResultDTO getOrderRecordList(HttpServletRequest request, @Param("orderNo") String orderNo) {
        UserDTO userDTO = getUserInfo(request);
        List<OrderRecord> recordList = rechargeRecordService.findByUserId(userDTO.getUserId());
        return new ResultDTO(200, "success", recordList);
    }

    /**
     * 是否开通且可用次数
     *
     * @return
     */
    @GetMapping("isOpenAndCount")
    @ResponseBody
    public ResultDTO isOpenAndCount(HttpServletRequest request) {
        UserDTO userDTO = getUserInfo(request);
        logger.info("[免费乘公交][是否开通且可用次数][userId][{}][form][{}]", userDTO, null);
        Map<String, Object> openAndCount = userBusCardService.isOpenAndCount(userDTO);
        ResultDTO resultDTO = this.getSuccessResult("是否开通且可用次数", openAndCount);
        logger.info("[免费乘公交][是否开通且可用次数][userId][{}][form][{}][result][{}]", userDTO, null, resultDTO);
        return resultDTO;
    }

    /**
     * 是否为车主
     *
     * @return
     */
    @GetMapping("isCarMaster")
    @ResponseBody
    public ResultDTO isCarMaster(HttpServletRequest request) {
        UserDTO userDTO = getUserInfo(request);
        logger.info("[免费乘公交][是否为车主][userId][{}][form][{}]", userDTO, null);
        Boolean carMaster = outService.isCarMaster(userDTO.getAuthName(), userDTO.getAuthCardNo());
        ResultDTO resultDTO = this.getSuccessResult("是否为车主", carMaster);
        logger.info("[免费乘公交][是否为车主][userId][{}][form][{}][result][{}]", userDTO, null, resultDTO);
        return resultDTO;
    }

    /**
     * 是否为车主
     *
     * @return
     */
    @PostMapping("getStationInfo")
    @ResponseBody
    public ResultDTO getStationInfo(@RequestBody StationInfoForm form) {
        this.beanValidator(form);
        logger.info("[免费乘公交][根据经纬度获取车站信息][userId][{}][form][{}]", null, form);
        ResultDTO stationInfo = publicTrafficService.getStationInfo(form);
        logger.info("[免费乘公交][根据经纬度获取车站信息][userId][{}][form][{}][result][{}]", null, form, stationInfo);
        return stationInfo;
    }
}
